<template>
  <div class="performance-page">
    <div class="page-header">
      <h2>绩效考核</h2>
      <div class="header-actions">
        <el-button type="primary" icon="Plus" @click="showAddDialog = true">创建考核计划</el-button>
        <el-button icon="Download">导出</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #e8f4ff">
            <el-icon color="#409eff" :size="24"><Opportunity /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalPlans }}</div>
            <div class="stat-label">考核计划</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #fff5e8">
            <el-icon color="#fa8c16" :size="24"><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalEmployees }}</div>
            <div class="stat-label">考核员工</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #e8fff3">
            <el-icon color="#52c41a" :size="24"><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #fff0f0">
            <el-icon color="#ff4d4f" :size="24"><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.pending }}</div>
            <div class="stat-label">待评估</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="考核周期">
          <el-select v-model="filterForm.period" placeholder="请选择周期" clearable>
            <el-option label="月度考核" value="monthly" />
            <el-option label="季度考核" value="quarterly" />
            <el-option label="年度考核" value="yearly" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="filterForm.department" placeholder="请选择部门" clearable>
            <el-option label="技术部" value="tech" />
            <el-option label="销售部" value="sales" />
            <el-option label="市场部" value="marketing" />
            <el-option label="人力资源部" value="hr" />
            <el-option label="财务部" value="finance" />
          </el-select>
        </el-form-item>
        <el-form-item label="考核状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
            <el-option label="待审核" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 绩效考核内容 -->
    <el-card class="table-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="考核计划" name="plans">
          <el-table :data="planList" stripe>
            <el-table-column prop="name" label="考核名称" width="180" />
            <el-table-column prop="period" label="考核周期" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.periodText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="startDate" label="开始日期" width="120" />
            <el-table-column prop="endDate" label="结束日期" width="120" />
            <el-table-column prop="participants" label="参与人数" width="100" align="center">
              <template #default="{ row }">
                <el-tag type="primary">{{ row.participants }}人</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="completionRate" label="完成率" width="150" align="center">
              <template #default="{ row }">
                <el-progress :percentage="row.completionRate" />
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ row.statusText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewPlan(row)">详情</el-button>
                <el-button link type="success" @click="viewResults(row)">考核结果</el-button>
                <el-button link type="primary" @click="editPlan(row)">编辑</el-button>
                <el-button link type="danger" @click="deletePlan(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="员工绩效" name="employee">
          <el-table :data="employeeList" stripe>
            <el-table-column prop="name" label="员工姓名" width="120" />
            <el-table-column prop="employeeId" label="工号" width="100" />
            <el-table-column prop="department" label="部门" width="120" />
            <el-table-column prop="position" label="职位" width="120" />
            <el-table-column prop="period" label="考核周期" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.periodText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="绩效得分" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getScoreType(row.score)" size="large">{{ row.score }}分</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="rating" label="绩效等级" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getRatingType(row.rating)">{{ row.ratingText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getEvaluationStatusType(row.status)">{{ row.statusText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="220">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewDetail(row)">详情</el-button>
                <el-button link type="success" @click="evaluate(row)">评估</el-button>
                <el-button link type="warning" @click="viewHistory(row)">历史</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="KPI指标" name="kpi">
          <el-button type="primary" icon="Plus" @click="showKpiDialog = true" style="margin-bottom: 15px">添加KPI</el-button>
          <el-table :data="kpiList" stripe>
            <el-table-column prop="name" label="指标名称" width="180" />
            <el-table-column prop="category" label="指标类别" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.category }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="department" label="适用部门" width="120" />
            <el-table-column prop="weight" label="权重" width="100" align="center">
              <template #default="{ row }">
                {{ row.weight }}%
              </template>
            </el-table-column>
            <el-table-column prop="target" label="目标值" width="120" align="center" />
            <el-table-column prop="unit" label="单位" width="80" align="center" />
            <el-table-column prop="calculationMethod" label="计算方法" width="150" />
            <el-table-column label="操作" fixed="right" width="180">
              <template #default="{ row }">
                <el-button link type="primary" @click="editKpi(row)">编辑</el-button>
                <el-button link type="danger" @click="deleteKpi(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="绩效分析" name="analysis">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>绩效等级分布</span>
                  </div>
                </template>
                <div class="chart-container" ref="ratingChartRef">
                  <div style="text-align: center; padding: 100px 0; color: #909399">
                    绩效等级分布图表
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>部门绩效对比</span>
                  </div>
                </template>
                <div class="chart-container" ref="departmentChartRef">
                  <div style="text-align: center; padding: 100px 0; color: #909399">
                    部门绩效对比图表
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="24">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>绩效趋势分析</span>
                  </div>
                </template>
                <div class="chart-container" ref="trendChartRef">
                  <div style="text-align: center; padding: 100px 0; color: #909399">
                    绩效趋势分析图表
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="绩效改进" name="improvement">
          <el-table :data="improvementList" stripe>
            <el-table-column prop="employeeName" label="员工姓名" width="120" />
            <el-table-column prop="department" label="部门" width="120" />
            <el-table-column prop="score" label="当前得分" width="100" align="center" />
            <el-table-column prop="improvementArea" label="改进方向" width="180" />
            <el-table-column prop="action" label="改进措施" width="200" />
            <el-table-column prop="mentor" label="辅导人" width="100" />
            <el-table-column prop="deadline" label="完成期限" width="120" />
            <el-table-column prop="progress" label="进度" width="150" align="center">
              <template #default="{ row }">
                <el-progress :percentage="row.progress" />
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewImprovementPlan(row)">查看计划</el-button>
                <el-button link type="success" @click="updateProgress(row)">更新进度</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑考核计划对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="dialogTitle"
      width="700px"
    >
      <el-form :model="planForm" :rules="rules" ref="planFormRef" label-width="100px">
        <el-form-item label="考核名称" prop="name">
          <el-input v-model="planForm.name" placeholder="请输入考核名称" />
        </el-form-item>
        <el-form-item label="考核周期" prop="period">
          <el-select v-model="planForm.period" placeholder="请选择周期">
            <el-option label="月度考核" value="monthly" />
            <el-option label="季度考核" value="quarterly" />
            <el-option label="年度考核" value="yearly" />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="planForm.startDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="planForm.endDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="考核范围" prop="scope">
          <el-checkbox-group v-model="planForm.scope">
            <el-checkbox label="tech">技术部</el-checkbox>
            <el-checkbox label="sales">销售部</el-checkbox>
            <el-checkbox label="marketing">市场部</el-checkbox>
            <el-checkbox label="hr">人力资源部</el-checkbox>
            <el-checkbox label="finance">财务部</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="考核说明" prop="description">
          <el-input
            v-model="planForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入考核说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加KPI对话框 -->
    <el-dialog v-model="showKpiDialog" title="添加KPI指标" width="600px">
      <el-form :model="kpiForm" label-width="100px">
        <el-form-item label="指标名称">
          <el-input v-model="kpiForm.name" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="指标类别">
          <el-select v-model="kpiForm.category" placeholder="请选择类别">
            <el-option label="业绩指标" value="performance" />
            <el-option label="能力指标" value="capability" />
            <el-option label="态度指标" value="attitude" />
            <el-option label="行为指标" value="behavior" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用部门">
          <el-select v-model="kpiForm.department" placeholder="请选择部门">
            <el-option label="技术部" value="tech" />
            <el-option label="销售部" value="sales" />
            <el-option label="市场部" value="marketing" />
            <el-option label="全部" value="all" />
          </el-select>
        </el-form-item>
        <el-form-item label="权重">
          <el-input-number v-model="kpiForm.weight" :min="1" :max="100" />
          <span style="margin-left: 10px">%</span>
        </el-form-item>
        <el-form-item label="目标值">
          <el-input v-model="kpiForm.target" placeholder="请输入目标值" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="kpiForm.unit" placeholder="如：万元、%、次" />
        </el-form-item>
        <el-form-item label="计算方法">
          <el-input v-model="kpiForm.calculationMethod" placeholder="请输入计算方法" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showKpiDialog = false">取消</el-button>
        <el-button type="primary" @click="handleKpiSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 统计数据
const stats = reactive({
  totalPlans: 12,
  totalEmployees: 186,
  completed: 132,
  pending: 54
})

// 筛选表单
const filterForm = reactive({
  period: '',
  department: '',
  status: ''
})

// 当前标签页
const activeTab = ref('plans')

// 考核计划列表
const planList = ref([
  {
    id: 1,
    name: '2025年第一季度绩效考核',
    period: 'quarterly',
    periodText: '季度考核',
    startDate: '2025-01-01',
    endDate: '2025-03-31',
    participants: 186,
    completionRate: 75,
    status: 'ongoing',
    statusText: '进行中'
  },
  {
    id: 2,
    name: '2024年度绩效考核',
    period: 'yearly',
    periodText: '年度考核',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    participants: 178,
    completionRate: 100,
    status: 'completed',
    statusText: '已完成'
  }
])

// 员工绩效列表
const employeeList = ref([
  {
    id: 1,
    name: '张三',
    employeeId: 'E001',
    department: '技术部',
    position: '高级工程师',
    period: 'quarterly',
    periodText: 'Q1 2025',
    score: 92,
    rating: 'A',
    ratingText: '优秀',
    status: 'completed',
    statusText: '已完成'
  },
  {
    id: 2,
    name: '李四',
    employeeId: 'E002',
    department: '销售部',
    position: '销售经理',
    period: 'quarterly',
    periodText: 'Q1 2025',
    score: 88,
    rating: 'B',
    ratingText: '良好',
    status: 'completed',
    statusText: '已完成'
  },
  {
    id: 3,
    name: '王五',
    employeeId: 'E003',
    department: '市场部',
    position: '市场专员',
    period: 'quarterly',
    periodText: 'Q1 2025',
    score: 78,
    rating: 'C',
    ratingText: '合格',
    status: 'pending',
    statusText: '待评估'
  }
])

// KPI指标列表
const kpiList = ref([
  {
    id: 1,
    name: '销售额完成率',
    category: '业绩指标',
    department: '销售部',
    weight: 40,
    target: '100',
    unit: '%',
    calculationMethod: '实际销售额/目标销售额×100%'
  },
  {
    id: 2,
    name: '项目按时完成率',
    category: '业绩指标',
    department: '技术部',
    weight: 35,
    target: '95',
    unit: '%',
    calculationMethod: '按时完成项目数/总项目数×100%'
  },
  {
    id: 3,
    name: '团队协作能力',
    category: '能力指标',
    department: '全部',
    weight: 15,
    target: '85',
    unit: '分',
    calculationMethod: '360度评估得分'
  }
])

// 绩效改进列表
const improvementList = ref([
  {
    id: 1,
    employeeName: '王五',
    department: '市场部',
    score: 78,
    improvementArea: '客户沟通技巧',
    action: '参加客户服务培训课程',
    mentor: '李经理',
    deadline: '2025-03-31',
    progress: 60
  },
  {
    id: 2,
    employeeName: '赵六',
    department: '技术部',
    score: 72,
    improvementArea: '项目管理能力',
    action: '参与项目管理实践',
    mentor: '张总监',
    deadline: '2025-04-30',
    progress: 40
  }
])

// 对话框
const showAddDialog = ref(false)
const showKpiDialog = ref(false)
const dialogTitle = computed(() => planForm.id ? '编辑考核计划' : '创建考核计划')
const planFormRef = ref(null)

// 考核表单
const planForm = reactive({
  id: null,
  name: '',
  period: '',
  startDate: '',
  endDate: '',
  scope: [],
  description: ''
})

// KPI表单
const kpiForm = reactive({
  name: '',
  category: '',
  department: '',
  weight: 20,
  target: '',
  unit: '',
  calculationMethod: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入考核名称', trigger: 'blur' }],
  period: [{ required: true, message: '请选择考核周期', trigger: 'change' }]
}

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    ongoing: 'warning',
    completed: 'success',
    pending: 'info'
  }
  return types[status] || 'info'
}

// 获取分数类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 60) return 'warning'
  return 'danger'
}

// 获取等级类型
const getRatingType = (rating) => {
  const types = {
    'A': 'success',
    'B': 'primary',
    'C': 'warning',
    'D': 'danger'
  }
  return types[rating] || 'info'
}

// 获取评估状态类型
const getEvaluationStatusType = (status) => {
  const types = {
    completed: 'success',
    pending: 'warning',
    reviewing: 'info'
  }
  return types[status] || 'info'
}

// 搜索
const handleSearch = () => {
  console.log('搜索', filterForm)
  ElMessage.success('搜索成功')
}

// 重置
const handleReset = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  ElMessage.success('已重置')
}

// 切换标签页
const handleTabClick = (tab) => {
  console.log('切换到', tab.props.name)
}

// 查看计划
const viewPlan = (row) => {
  console.log('查看计划', row)
  ElMessage.info('查看计划详情')
}

// 查看结果
const viewResults = (row) => {
  console.log('查看结果', row)
  ElMessage.info('查看考核结果')
}

// 编辑计划
const editPlan = (row) => {
  Object.assign(planForm, row)
  showAddDialog.value = true
}

// 删除计划
const deletePlan = (row) => {
  ElMessageBox.confirm('确定要删除该考核计划吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = planList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      planList.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 查看详情
const viewDetail = (row) => {
  console.log('查看详情', row)
  ElMessage.info('查看员工绩效详情')
}

// 评估
const evaluate = (row) => {
  console.log('评估', row)
  ElMessage.success('开始评估')
}

// 查看历史
const viewHistory = (row) => {
  console.log('查看历史', row)
  ElMessage.info('查看历史绩效')
}

// 编辑KPI
const editKpi = (row) => {
  console.log('编辑KPI', row)
  ElMessage.info('编辑KPI指标')
}

// 删除KPI
const deleteKpi = (row) => {
  ElMessageBox.confirm('确定要删除该KPI指标吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = kpiList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      kpiList.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 查看改进计划
const viewImprovementPlan = (row) => {
  console.log('查看改进计划', row)
  ElMessage.info('查看改进计划详情')
}

// 更新进度
const updateProgress = (row) => {
  console.log('更新进度', row)
  ElMessage.success('进度更新成功')
}

// 提交表单
const handleSubmit = () => {
  planFormRef.value.validate((valid) => {
    if (valid) {
      console.log('提交表单', planForm)
      ElMessage.success('保存成功')
      showAddDialog.value = false
    }
  })
}

// 提交KPI表单
const handleKpiSubmit = () => {
  console.log('提交KPI', kpiForm)
  ElMessage.success('KPI添加成功')
  showKpiDialog.value = false
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}
</script>

<style scoped lang="scss">
.performance-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .stat-icon {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    margin-right: 15px;
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  .card-header {
    font-weight: bold;
    font-size: 16px;
  }

  .chart-container {
    height: 300px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

